package com.kuaifawu.lwnlawyerclient.Activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.kuaifawu.lwnlawyerclient.Adapter.LWNAdapter_growLevel;
import com.kuaifawu.lwnlawyerclient.Adapter.LWNAdapter_growXunzhang;
import com.kuaifawu.lwnlawyerclient.Adapter.LWNAdapter_home;
import com.kuaifawu.lwnlawyerclient.LWNNetwork.LWNNetworkCenter;
import com.kuaifawu.lwnlawyerclient.Lib.ToastView_custom;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_lawyerInfo;
import com.kuaifawu.lwnlawyerclient.Model.LWNModel_user;
import com.kuaifawu.lwnlawyerclient.R;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wyk123 on 2015/7/17.
 */
public class GrowMedalActivity extends Activity implements View.OnClickListener {
    @ViewInject(R.id.grow_cursor)
    private ImageView cursor;// 动画图片
    @ViewInject(R.id.grow_level)
    private TextView textView_level;
    @ViewInject(R.id.grow_xunzhang)
    private TextView textView_xunzhang;
    @ViewInject(R.id.grow_jifen)
    private TextView textView_jifen;
    @ViewInject(R.id.viewpager_grow)
    private ViewPager pagerView_grow=null;
    @ViewInject(R.id.growmedal_back)
    private ImageButton growmedal_back=null;

    private List<View> listViews; // Tab页面列表
    LayoutInflater mInflater;
    private int move = 0;// 页卡1 -> 页卡2 偏移量
    private int currIndex = 0;// 当前页卡编号

    private ExpandableListView listView_level;
    private int setId=0;
    private WebView jifen_web;
    private String jifenUrl="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_growmedal);
        Intent intent=getIntent();
        Bundle bundle=intent.getExtras();

        if(bundle!=null){
            if(bundle.containsKey("index")){
                currIndex= bundle.getInt("index");
            }
        }
        ViewUtils.inject(this);
        if (move == 0) {
            DisplayMetrics dm = new DisplayMetrics();
            this.getWindowManager().getDefaultDisplay().getMetrics(dm);
            move = dm.widthPixels / 3;// 页卡1 -> 页卡2 偏移量
        }
        InitView();//必须调用否则无网络状态下会导致崩溃
        getlevelFromNetwork();
    }
    private void InitView(){
        jifenUrl="http://api.test.kuaifawu.com/LWNLayerClient/mygrowth";
        Matrix matrix = new Matrix();
        matrix.postTranslate(0, 0);
        cursor.setImageMatrix(matrix);// 设置动画初始位置

        textView_level.setOnClickListener(new MyGrowOnClickListener(0));
        textView_xunzhang.setOnClickListener(new MyGrowOnClickListener(1));
        textView_jifen.setOnClickListener(new MyGrowOnClickListener(2));
        growmedal_back.setOnClickListener(this);
        setPager();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.growmedal_back:
                finish();
                break;
        }
    }
    private void skipWeb(String url){
        jifen_web.loadUrl(url);
        WebSettings settings=jifen_web.getSettings();
        settings.setJavaScriptEnabled(true);
        jifen_web.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

    }
    private  View view_level=null;
    private  View view_xunzhang=null;
    private  View view_jifen=null;
    private void setPager(){

        if(listViews==null){
            listViews = new ArrayList<View>();
        }

//        View view_level = mInflater.inflate(R.layout.view_grow_level, null);
        View view_level = getLayoutInflater().inflate(R.layout.view_grow_level, null);
        View view_xunzhang = getLayoutInflater().inflate(R.layout.view_grow_xunzhang, null);
        View view_jifen = getLayoutInflater().inflate(R.layout.view_grow_jifen, null);
        listViews.add(view_level);
        listViews.add(view_xunzhang);
        listViews.add(view_jifen);
        pagerView_grow.setAdapter(new LWNAdapter_home(listViews));
        pagerView_grow.setOnPageChangeListener(new MyOnPageChangeListener());
        pagerView_grow.setCurrentItem(currIndex);
    }

    private class MyGrowOnClickListener implements View.OnClickListener {
        private int index = 0;

        public MyGrowOnClickListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View v) {
            switch (index) {
                case 0: {
                    textView_level.setTextColor(getResources().getColor(R.color.theme_color));
                    textView_xunzhang.setTextColor(getResources().getColor(R.color.color_item_content));
                    textView_jifen.setTextColor(getResources().getColor(R.color.color_item_content));
                }
                break;
                case 1: {
                    textView_level.setTextColor(getResources().getColor(R.color.color_item_content));
                    textView_xunzhang.setTextColor(getResources().getColor(R.color.theme_color));
                    textView_jifen.setTextColor(getResources().getColor(R.color.color_item_content));
                }
                break;
                case 2: {
                    textView_level.setTextColor(getResources().getColor(R.color.color_item_content));
                    textView_xunzhang.setTextColor(getResources().getColor(R.color.theme_color));
                    textView_jifen.setTextColor(getResources().getColor(R.color.theme_color));
                }
                break;
            }
            pagerView_grow.setCurrentItem(index);
        }
    }


    /**
     * 页卡切换监听
     */
    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
        int one = move;// 页卡1 -> 页卡2 偏移量

        @Override
        public void onPageSelected(int arg0) {
            Animation animation = new TranslateAnimation(one * currIndex, one * arg0, 0, 0);
            cursor.startAnimation(animation);
            switch (arg0) {
                case 0: {
                    textView_level.setTextColor(getResources().getColor(R.color.theme_color));
                    textView_xunzhang.setTextColor(getResources().getColor(R.color.color_item_content));
                    textView_jifen.setTextColor(getResources().getColor(R.color.color_item_content));
                }
                break;
                case 1: {
                    textView_level.setTextColor(getResources().getColor(R.color.color_item_content));
                    textView_xunzhang.setTextColor(getResources().getColor(R.color.theme_color));
                    textView_jifen.setTextColor(getResources().getColor(R.color.color_item_content));
                }
                break;
                case 2: {
                    textView_level.setTextColor(getResources().getColor(R.color.color_item_content));
                    textView_xunzhang.setTextColor(getResources().getColor(R.color.color_item_content));
                    textView_jifen.setTextColor(getResources().getColor(R.color.theme_color));
                }
                break;
            }

            currIndex = arg0;
            animation.setFillAfter(true);// True:图片停在动画结束位置
            animation.setDuration(300);
            cursor.startAnimation(animation);
        }


        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            if(arg0==2){

            }

        }
    }

    /**
     * 获取等级
     */
    public void getlevelFromNetwork() {
        final ProgressDialog proDialog = android.app.ProgressDialog.show(this, "", getResources().getString(R.string.toast_wait));

        LWNNetworkCenter center = LWNNetworkCenter.getInstance();
        if(!center.checkNetworkState(this)){
            proDialog.dismiss();
//            ToastView_custom toast = new ToastView_custom(this);
//            toast.showCustom(this, getResources().getDrawable(R.drawable.error), "请连接网络，稍后重试...");

            ToastView_custom toast = new ToastView_custom(GrowMedalActivity.this);
            toast.showCustom(GrowMedalActivity.this, "请连接网络，稍后重试...");
            return;
        }
        String string_url = center.getInstance().getGrowInfo(this);
        HttpUtils http = center.getUtils();
        http.configDefaultHttpCacheExpiry(0*0);
        http.send(HttpRequest.HttpMethod.GET,
                string_url,
                new RequestCallBack<Object>() {
                    @Override
                    public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                        //         proDialog.dismiss();
                        try {
                            proDialog.dismiss();
                            JSONObject jsonObject = new JSONObject(objectResponseInfo.result.toString());
                            String string_code = jsonObject.getString("code");
                            String string_msg = jsonObject.getString("msg");

                            switch (String.valueOf(string_code)) {
                                case "10000": {
                                    JSONObject object = jsonObject.getJSONObject("data");
                                    LWNModel_lawyerInfo lawyerInfo = LWNModel_lawyerInfo.getInstance();
                                    lawyerInfo.setString_class(object.getString("class"));
                                    lawyerInfo.setIntegral(object.getString("integral"));
                                    lawyerInfo.setLabel(object.getString("label"));
                                    lawyerInfo.setNextintegral(object.getString("nextintegral"));

                                    //InitView();
                                    InitViewPager();
                                }
                                break;
                                case "10001": {
//                                    Toast toast = Toast.makeText(this.getApplicationContext(),
//                                            string_msg, Toast.LENGTH_SHORT);
//                                    toast.setGravity(Gravity.CENTER, 0, 0);
//                                    LinearLayout toastView = (LinearLayout) toast.getView();
//                                    ImageView imageCodeProject = new ImageView(this.getApplicationContext());
//                                    imageCodeProject.setImageResource(R.drawable.error);
//                                    toastView.addView(imageCodeProject, 0);
//                                    toast.show();
//                                    ToastView_custom toast = new ToastView_custom(GrowMedalActivity.this);
//                                    toast.showCustom(GrowMedalActivity.this, getResources().getDrawable(R.drawable.error), string_msg);

                                    ToastView_custom toast = new ToastView_custom(GrowMedalActivity.this);
                                    toast.showCustom(GrowMedalActivity.this, string_msg);
                                }
                                break;
                                case "10003": {
                                    String token = LWNModel_user.getInstance().getString_token(GrowMedalActivity.this);
                                    if (token != null) {
                                        Toast toast = Toast.makeText(GrowMedalActivity.this.getApplicationContext(),
                                                string_msg, Toast.LENGTH_SHORT);
                                        toast.setGravity(Gravity.CENTER, 0, 0);
                                        LinearLayout toastView = (LinearLayout) toast.getView();
                                        ImageView imageCodeProject = new ImageView(GrowMedalActivity.this.getApplicationContext());
                                        imageCodeProject.setImageResource(R.drawable.error);
                                        toastView.addView(imageCodeProject, 0);
                                        toast.show();

                                        Intent intent = new Intent();
                                        intent.putExtra("name", "LeiPei");
                                        intent.setClass(GrowMedalActivity.this, LWNLoginActivity.class);
                                        startActivity(intent);
                                        GrowMedalActivity.this.finish();
                                    }
                                }
                                break;
                                default: {
                                    Toast toast = Toast.makeText(GrowMedalActivity.this.getApplicationContext(),
                                            string_msg, Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    LinearLayout toastView = (LinearLayout) toast.getView();
                                    ImageView imageCodeProject = new ImageView(GrowMedalActivity.this.getApplicationContext());
                                    imageCodeProject.setImageResource(R.drawable.error);
                                    toastView.addView(imageCodeProject, 0);
                                    toast.show();
                                }
                                break;
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            //   proDialog.dismiss();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        //System.out.println(s);
                        proDialog.dismiss();
                    }

                    @Override
                    public void onCancelled() {

                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                }
        );
    }


    private void InitViewPager() {
        listViews = new ArrayList<View>();

        view_level = getLayoutInflater().inflate(R.layout.view_grow_level, null);
        view_xunzhang = getLayoutInflater().inflate(R.layout.view_grow_xunzhang, null);
        view_jifen = getLayoutInflater().inflate(R.layout.view_grow_jifen, null);
        jifen_web=(WebView)view_jifen.findViewById(R.id.jifen_web);
        skipWeb(jifenUrl);
        listViews.add(view_level);
        listViews.add(view_xunzhang);
        listViews.add(view_jifen);

        pagerView_grow.setAdapter(new LWNAdapter_home(listViews));

        pagerView_grow.setOnPageChangeListener(new MyOnPageChangeListener());
        pagerView_grow.setCurrentItem(currIndex);
        ExpandableListView expandableListView = (ExpandableListView) view_level.findViewById(R.id.gc_level);

        View headerView = getLayoutInflater().inflate(R.layout.item_growlevel_head, expandableListView, false);
        ImageView imageView_b = (ImageView)headerView.findViewById(R.id.gc_level_back);
        TextView textlevel_one = (TextView)headerView.findViewById(R.id.gc_level_one);
        TextView textlevel_two = (TextView)headerView.findViewById(R.id.gc_level_two);
        TextView textlevel_three = (TextView)headerView.findViewById(R.id.gc_level_three);
        TextView textlevel_content = (TextView)headerView.findViewById(R.id.gc_level_content);
        ProgressBar progressBar_level = (ProgressBar)headerView.findViewById(R.id.progress_level);
        TextView textlevel_score = (TextView)headerView.findViewById(R.id.gc_level_score);

        int level = Integer.parseInt(LWNModel_lawyerInfo.getInstance().getString_class());
        if(level == 1){
            imageView_b.setImageDrawable(getResources().getDrawable(R.drawable.gc_level_headbn));
            textlevel_one.setVisibility(View.INVISIBLE);
        }
        else{
            imageView_b.setImageDrawable(getResources().getDrawable(R.drawable.gc_level_headb));
            textlevel_one.setVisibility(View.VISIBLE);
            textlevel_one.setText("LV." + String.valueOf(level - 1));
        }

        int now = Integer.parseInt(LWNModel_lawyerInfo.getInstance().getIntegral());
        int next = Integer.parseInt(LWNModel_lawyerInfo.getInstance().getNextintegral());
        int need = next - now;

        textlevel_two.setText("LV." + String.valueOf(level));
        textlevel_three.setText("LV." + String.valueOf(level + 1));
        textlevel_content.setText("当前等级" + String.valueOf(level) + "级，距离下个等级还需要" + String.valueOf(need) + "积分");
        textlevel_score.setText(LWNModel_lawyerInfo.getInstance().getNextintegral());
        float pro = Float.parseFloat(LWNModel_lawyerInfo.getInstance().getIntegral())/ Float.parseFloat(LWNModel_lawyerInfo.getInstance().getNextintegral());
        int int_pro = (int)(pro *100);
        progressBar_level.setProgress(int_pro);

        expandableListView.addHeaderView(headerView);
        expandableListView.setGroupIndicator(null);
        expandableListView.setAdapter(new LWNAdapter_growLevel(this));

        ListView listView_xunzhang = (ListView) view_xunzhang.findViewById(R.id.list_xunzhang);
        LWNAdapter_growXunzhang xunzhang =  new LWNAdapter_growXunzhang(view_xunzhang.getContext(), R.layout.view_grow_xunzhang, null,this);
        listView_xunzhang.setAdapter(xunzhang);
    }
}
